package com.academy.teacher;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ListView;

import com.academy.querystapp.R;
import com.academy.services.BaseService;
import com.academy.services.RequestMethod;
import com.academy.services.ResponseListener;

import com.academy.util.AcademyUtility;

public class ViewQuestionActivity extends Activity implements ResponseListener
{
	
	String message, title;
	String strQuestion,StrVisitingCount,strPostedID,strAskedBy;
	
	
	private ArrayList<QuestionDetail> questionDetailsList;
	ListView lvViewQuestion;
	QuestionDetail questionDetail;
	Timer  timer ;
	TimerTask task;
	
    public void onCreate(Bundle savedInstanceState) 
    {
    	 super.onCreate(savedInstanceState);
    	 setContentView(R.layout.view_question_listview);
    	 initializeViews();
    	 
    }
    
    @Override
    protected void onResume() 
    {
    	// TODO Auto-generated method stub
    	super.onResume();
    	questionDetailsList.clear();
    	getListofQuestions(true);
    }
    
    public void initializeViews()
    {
    	lvViewQuestion=(ListView) findViewById(R.id.listView1);
    	questionDetailsList=new ArrayList<QuestionDetail>();
    }
    
//    public void getListofQuestions()
//    {
//    
//    					
//    	BaseService baseService = new BaseService(this, this, RequestMethod.GET);//();
//    	baseService.addParam(getString(R.string.TeacherID_param), AcademyUtility.getTeacherID());
//    	baseService.addParam(getString(R.string.userType_Param),"ViewStudentPostedQuery");
//    	baseService.execute(getString(R.string.viewStudentPostURL));
//    										
//	}
    
    public void getListofQuestions(boolean progrss)
    {				
    	BaseService service  = new BaseService(this, this, RequestMethod.GET);  
    	if(!progrss)
    		service.isProgressAvailable = false;
    	service.addParam(getString(R.string.TeacherID_param), AcademyUtility.getTeacherID());
    	service.addParam(getString(R.string.userType_Param),"ViewStudentPostedQuery");
    	service.execute(getString(R.string.viewStudentPostURL));							
	}
    
    


private void parseResponse(String response)
{
	if(response==null ||response.equals("null"))
	{
		System.out.println("Response ---> "+response);
				
		showAlert(null, "No Server Found!");
	}
	else
	{
		try 
		{ 
			questionDetailsList.clear();
			JSONObject RootObject = new JSONObject(response);
			System.out.println("JSON Object==> "+RootObject.toString());
			JSONObject studentPostObject = RootObject.getJSONObject("studentPost");
			
			String strStatus=studentPostObject.getString("status");
			
			if(strStatus.equals("true"))
			{			
				int noOfRows=Integer.parseInt(studentPostObject.getString("noOfRows"));
				if(noOfRows==1)
				{
					JSONObject singleObject=studentPostObject.getJSONObject("studentPostData");
					strQuestion=singleObject.getString("question");
					StrVisitingCount=singleObject.getString("visitedCount");
					strPostedID=singleObject.getString("postID");
					strAskedBy=singleObject.getString("studentID");
					
					System.out.println("strQuestion="+strQuestion);
					questionDetail=new QuestionDetail();
					questionDetail.setQuestion(strQuestion);
					questionDetail.setVisitingCount(StrVisitingCount);
					questionDetail.setPostedID(strPostedID);
					questionDetail.setAskedBy(strAskedBy);
					questionDetailsList.add(questionDetail);
					System.out.println("questionDetailsList"+questionDetailsList);
				}
				else if(noOfRows>1)
				{
					JSONArray studentPostArray=studentPostObject.getJSONArray("studentPostData");
					System.out.println("studentPostArray="+studentPostArray);
					int length=studentPostArray.length();
					System.out.println("length count="+length);
					
	//				JSONObject studentPostDataObject;
					
					for(int m=0;m<length;m++)
					{
						JSONObject studentPostDataObject=studentPostArray.getJSONObject(m);
						System.out.println("studentPostDataObject="+studentPostDataObject);
						strQuestion=studentPostDataObject.getString("question");
						StrVisitingCount=studentPostDataObject.getString("visitedCount");
						strPostedID=studentPostDataObject.getString("postID");
						strAskedBy=studentPostDataObject.getString("studentID");
						
						System.out.println("strQuestion="+strQuestion);
						questionDetail=new QuestionDetail();
						questionDetail.setQuestion(strQuestion);
						questionDetail.setVisitingCount(StrVisitingCount);
						questionDetail.setPostedID(strPostedID);
						questionDetail.setAskedBy(strAskedBy);
						questionDetailsList.add(questionDetail);
						System.out.println("questionDetailsList"+questionDetailsList);
					}
					System.out.println("questionDetailsList sancmn="+questionDetailsList);
				}
				setAdapterForQuestionDetailList();
				
//				showAlert(null, "post in");
//				AcademyUtility.setName(studentData.getString("studentName"));
//				AcademyUtility.setCollegeName(studentData.getString("collageName"));
//				AcademyUtility.setCoarse(studentData.getString("course"));
//				AcademyUtility.setEmailID(studentData.getString("emailID"));
//				AcademyUtility.setStudentID(strUserName);
//				Intent ii=new Intent(this,QueryTabActivity.class);
//				startActivity(ii);
			}
			else if(strStatus.equals("false"))
			{	
				JSONObject studentPostDataObject= studentPostObject.getJSONObject("studentPostData");
				String strError= studentPostDataObject.getString("errorDesc");
				showAlertFalse(null, strError);
			}
		}
		catch (JSONException e) 
		{
			e.printStackTrace();
		} 
	}
}

	public void showAlert(String Title,String Message)
	{
		Builder builder = new Builder(this);
		builder.setTitle(Title);
		builder.setMessage(Message);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int arg1)
			{	
//				Intent i=new Intent(StudentActivity.this,Homepage.class);
//				startActivity(i);
//				finish();
				
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();	
	}
	
	public void showAlertFalse(String Title,String Message)
	{
		Builder builder = new Builder(this);
		builder.setTitle(Title);
		builder.setMessage(Message);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int arg1)
			{	
				Intent i=new Intent(ViewQuestionActivity.this,TeacherTabActivity.class);
				startActivity(i);
				finish();				
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();	
	}

	public void setAdapterForQuestionDetailList()
	{
		lvViewQuestion.setAdapter(new QuestionAdapter(getApplicationContext(), R.layout.question_list_item, questionDetailsList, this));
		sendContinousRequest();
	}
	
	public void passIntentToReplyToStudentQueryActivity(int postion)
	{
		QuestionDetail selectedQuestionDetail = questionDetailsList.get(postion);
		Intent ii =new Intent(this,ReplyToStudentQueries.class);
		ii.putExtra("strPostedID", selectedQuestionDetail.getPostedID());
		ii.putExtra("strQuestion", selectedQuestionDetail.getQuestion());
		ii.putExtra("strAskedBy", selectedQuestionDetail.getAskedBy());
		ii.putExtra("StrVisitingCount", selectedQuestionDetail.getVisitingCount());
		startActivity(ii);
	}

	@Override
	public void onServiceCompleted(String response, String requestURL) {
		parseResponse(response);
		
	}

	@Override
	public void onServiceFailed(String exception, String requestURL) {
		// TODO Auto-generated method stub
		
	}
    
	private void sendContinousRequest() {
		if(timer != null)
		{
			timer.cancel();
			timer.purge();
		}
		
		timer = new Timer();
    	task = new TimerTask() {
		
		@Override
		public void run() {
			getListofQuestions(false);
			
		}
    	};
		
		timer.schedule(task, 1000, 30000);
		
	}
}